<?php
     require_once('includes/includes.php');
     require_once('classes/class.content.inc.php');
	 require_once('classes/class.color.inc.php'); ##
	$listingUrl = $BASE_HREF."contentlisting.php";
     $loginUrl = $BASE_HREF."login.php";
     if (!$GENOBJ->isLoggedIn()) {
          $GENOBJ->redirect($loginUrl);
     }
     $BLACKOTEK_PAGE_TITLE = 'Content Page';
     $GENOBJ->clearSessionErrorMessages();
     $title = '';
     $body = '';
     $id = '';
     $status = 'Active';
	$mode = 'insert';
	$contentObj = new content();          
	
	$colorobj = new color(); ##
	$colors = Array('');
     if ( isset( $_GET['id'] ) ) {
     	if ( (trim($_GET['id'] ) == '' ) ) {
     		$GENOBJ->redirect($listingUrl);
     		exit;
		}
		$id = $_GET['id'];
		$mode = 'edit'; 
	}
	
	if ( isset( $_POST['id'] ) ) {
     	if ( (trim($_POST['id'] ) == '' ) ) {
     		$GENOBJ->redirect($listingUrl);
     		exit;
		}
		$id = $_POST['id'];
		$mode = 'edit'; 
	}
	
	if ($mode == 'edit') {
		$contentData = $contentObj->select($id);
		$filterArray = Array("utfdecode"); //Utf change
     	$contentData = $GENOBJ->filter($contentData, $filterArray); //Utf change
		
		$id = $contentData['id'];
		$title = $contentData['title'];
	    $body = $contentData['body'];
		$status = $contentData['status'];
	    $colors = $colorobj->getColorByProductId($id); #
	}
	$errorMessageArray = Array();
     if ($_POST) {
		$colors = $_POST['color'];
     	$filterElements = Array();
     	$filterArray = Array("utfencode","TrimElement", "htmlEntity");  //Utf change
     	$filterElements['id'] = $_POST['id'];
     	$filterElements['title'] = $_POST['title'];
	    $filterElements['body'] = $_POST['body'];
        $filterElements['status'] = $_POST['status'];
     	$filterElements = $GENOBJ->filter($filterElements, $filterArray);
		$id = $filterElements['id'];
		$title = $filterElements['title'];
          $body = $filterElements['body'];
          $status = $filterElements['status'];
          if ($GENOBJ->IsEmpty($title)) {
          	$errorMessageArray[] = 'Please enter  title'; 
		}
		/*
		 else {
        		if(!$GENOBJ->ValidAlphaNumeric($title)) {
        			$errorMessageArray[] = 'Title with only alphabets,numbers,dash and underscore allowed.';
			}
	   	}
	   	*/
		
		
		if ($GENOBJ->IsEmpty($body)) {
          	$errorMessageArray[] = 'Please enter content'; 
		}
		if ($GENOBJ->IsEmpty($status)) {
          	$errorMessageArray[] = 'Please select  status'; 
		}
          if (trim($_POST['id']) != '' ) {
          	$mode = 'edit';
		}
		
		if (count($errorMessageArray) <= 0) {
				
	     	if ($mode == 'insert') {
	     		$contentObj->settitle($title);
	     		$contentObj->setbody($body);
	     		$contentObj->setstatus($status);
	     		$contentexist = $contentObj->checkContentExists($title);
	     		$errorMessageArray[] = 'This title already exists. Try some other title';
	     		if (!$contentexist) {
	     			$insertId = $contentObj->insert();
					$colorArray =  $_POST['color']; #
					if ( count($colorArray) > 0  ) {
						foreach($colorArray as $_color ) {
							if (trim($_color) != '') {
								$clrAry[] = $_color;
								$colorobj->setpid($insertId);
								$colorobj->setcolor($_color);
								$colorobj->insert();
							}
						}
					}	
					##
					
	     			if ($insertId > 0) {
	     				$_SESSION['error']['contentinserted'] = 'Content inserted successfully';
	     				$GENOBJ->redirect($listingUrl);
					} else {
						 $_SESSION['error']['content-error'] = 'Error in insertion . Please try again!';	
						 $GENOBJ->redirect($listingUrl);
					}	
				} 
			} else {
				$contentObj->setid($id);
				$contentObj->settitle($title);
	     		$contentObj->setbody($body);
	     		$contentObj->setstatus($status);
	     		$contentObj->update($id);
				
				##
				$colorArray =  $_POST['color'];
				if ( count($colorArray) > 0  ) {
					foreach($colorArray as $_color ) {
						if (trim($_color) != '') {
							$clrAry[] = $_color;
						}
					}
				}	
				if ( count($clrAry) > 0  ) {
					$colorobj->delete($id);
					foreach($clrAry as $_clr ) {
						$colorobj->setpid($id);
						$colorobj->setcolor($_clr);
						$colorobj->insert();
					}
				}
				##

				
				
				
	     		$_SESSION['error']['contentupdated'] = 'Content updated successfully';
	     		$GENOBJ->redirect($listingUrl);
			}
		}
     }
?>
<?php include('templates/header.php');?>
<body>
	<div id="ncleangrey-container">
		<?php include('templates/navigation.php');?>
		<div class="breadcrumbs">
			<div id="nav-icons_all">
				<ul id="nav-icons">
					<li class="logout-icon"><a  title="Logout"  href="logout.php">Logout</a></li>
				</ul>
			</div>
               <p class="breadcrumbs">
                    <a title="Home" href="dashboard.php">Home</a> &#187; <a title="content" href="contentlisting.php">Content</a> &#187; <?php if($mode == 'edit'){?>Edit<?php }else { ?>Add<?php }?> Content
               </p>
		</div>
		<div class="hstippled">&nbsp;</div>
		<div id="MainContent">
			<div>
				<div class="pageerrorcontainer-validator">
					<div class="error-iterator"></div>
				</div>
			</div>
		<?php if(count($errorMessageArray) > 0):?>
			<div class="pageerrorcontainer">
			<?php foreach($errorMessageArray as $erroValue):?>
				<div class="pageoverflow">
					<img src="images/icons/system/stop.gif" class="systemicon" alt="Error" title="Error" />
					<label class="errorlabel"><?php echo $erroValue;?></label>
				</div>
			<?php endforeach;?>				
			</div>
		<?php endif;?>
               <div class="clearb">&nbsp;</div>
               <div id="Edit_Content_Result"></div>
               <div class="pagecontainer pageoverflow">
                    <div class="pageheader">
                      <?php if($mode == 'edit'){?>Edit<?php }else { ?>Add<?php }?> Content
                      <div class="field-required">* Fields are required </div>
                    </div>
                    <div style="clear: both;"></div>
                    <form method="post" action="content.php" name="contentfrm" id="contentfrm">
                    	<input type="hidden" id="id" value="<?php echo $id;?>" name="id">
                         <div id="page_content">
                              <div class="pageoverflow">
                                   <div class="pagetext">Title<span class="error-star">*</span>:</div>
                                   <div class="pageinput">
                                        <input type="text" name="title" id="title" value="<?php echo $title;?>" size="60"/>
                                   </div>
                              </div>
                              <div class="pageoverflow">
                                   <div class="pagetext">Content<span class="error-star">*</span>:</div>
                                   <div class="pageinput">
                                        <textarea id="body" name="body" cols="50" rows="10" ><?php echo $body;?></textarea>
                                   </div>
                              </div>
							
								<!-- ##-->
								   <?php if (count( $colors ) > 0 ): ?>
										<?php $i = 0; ?>	
									   <?php foreach($colors as $_color): ?>
										   <?php if ($i == 0): ?>
										   <div class="pageoverflow upload-color-container">	
											<p class="pagetext">Product Color :</p>
											   <p class="pageinput">
													<input type="text" name="color[]" id="title" value="<?php echo $_color;?>" size="20"/>
													<input type="button" name="Add color" value="Add color" class="add_color"/>
											   </p>
										   </div>
										   <?php else: ?>
										   <div class="pageoverflow upload-color-container">	
											<p class="pagetext">Product Color :</p>
											   <p class="pageinput">
													<input type="text" name="color[]" id="title" value="<?php echo $_color;?>" size="20"/>
													<input type="button" name="Add color" value="Add color" class="add_color"/>
													<input type="button" name="Remove Color" value="Remove Color" class="remove_color"/>
											   </p>
										   </div>
										   <?php endif;?>
										   <?php $i++;?>
									   <?php endforeach;?>
								   <?php endif;?>
							   <!-- ##-->
							
                              <div class="pageoverflow display-none">
                                   <div class="pagetext">Status<span class="error-star">*</span>:</div>
                                   <div class="pageinput">
                                        <select name="status">
                                             <option value="">none</option>
                                             <option value="Active" <?php echo ($status=='Active')?'selected':'selected'; ?> >Active</option>
                                             <option value="Inactive" <?php echo ($status=='Inactive')?'selected':''; ?> >Inactive</option>
                                        </select>
                                   </div>
                              </div>
                              <div class="pageoverflow">
                                   <p class="pagetext">&nbsp;</p>
                                   <p class="pageinput">
                                        <input type="submit" name="submitbutton" value="Submit" title="Save changes" />
                                        <input type="reset" name="apply" value="Reset" title="Save changes and continue to edit" />
                                   </p>
                              </div>
                              <div style="clear: both;"></div>
                         </div>
                    </form>
               </div>
               <p class="pageback">
				<a class="pageback" href="contentlisting.php">&#171; Back to Listing</a>
			</p>
               <div class="clearb"></div>
          </div>
     </div>
     <?php include('templates/footer.php');?>
</body>
<script>
$(document).ready(function(){

	$.validator.addMethod("alpha_numeric", function(value) {
		if (value.match(/^[a-zA-Z 0-9-_]+$/)){
			return true;
		} 
	}, 'Title with only alphabets,numbers,dash and underscore allowed.');

	var container = $('div.pageerrorcontainer-validator');
	$("#contentfrm").validate({
		errorContainer: container,
		errorLabelContainer: $("div.error-iterator", container),
		wrapper: 'div',
		rules: {
			title: {
				required: true
			}
		},
		messages: {
			title: {
				required: "Please enter title."
			}
		}
	});
	
	//##	
	var divContent = '<div class="pageoverflow upload-color-container">	\n\
	<p class="pagetext">Product Color :</p>\n\
	   <p class="pageinput">\n\
			<input type="text" name="color[]" id="title" value="" size="20"/>\n\
			<input type="button" name="Add color" value="Add color" class="add_color"/>\n\
			<input type="button" name="Remove Color" value="Remove Color" class="remove_color"/>\n\
	   </p>\n\
   </div>';
	
	$('.add_color').live('click', function() {
		var parent =  $(this).parents('div .upload-color-container');
        $(parent).after(divContent);
        return false;
	});
	
	$('.remove_color').live('click', function() {
		$(this).parents('div .upload-color-container').remove();
        return false;
	});
	
	
	
	//##
	
     /*
	var config = {
		filebrowserBrowseUrl :fck_filemanager_path + 'browser.html?Connector=' + fck_connector_url,
		filebrowserImageBrowseUrl : fck_filemanager_path + 'browser.html?Type=Image&Connector=' + fck_connector_url,
		filebrowserFlashBrowseUrl :fck_filemanager_path + 'browser.html?Type=Flash&Connector=' + fck_connector_url,
		toolbar :
			[
				['Source','Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
				['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker'],
				['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
				['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'],
				['Styles','Format','Font','FontSize'],
    				['TextColor','BGColor']
			]
	};
	$('#body').ckeditor(config );
     */
});
</script>
</html>
